from enum import Enum
from typing import Any
from uuid import UUID

from pydantic import BaseModel

def remove_fields(data_dict: dict, fields: list[str]) -> None:
    """根据传递的字段名移除字典中指定的字段"""
    for field in fields:
        data_dict.pop(field, None)

#剩余时间
def residue_datetime(ttl_seconds):
    """将TTL秒数转换为详细的年月日时分秒格式"""
    if ttl_seconds == -1:
        return "永不过期"
    elif ttl_seconds == -2:
        return "键不存在"
    else:
        # 计算详细的时间间隔
        days = ttl_seconds // (24 * 3600)
        ttl_seconds %= (24 * 3600)
        hours = ttl_seconds // 3600
        ttl_seconds %= 3600
        minutes = ttl_seconds // 60
        seconds = ttl_seconds % 60

        return f"{days}天 {hours}小时 {minutes}分钟 {seconds}秒"

#过期时间
def expired_datetime(ttl_value):
    days = ttl_value // (24 * 60 * 60)  # 30天
    hours = (ttl_value % (24 * 60 * 60)) // (60 * 60)  # 0小时
    minutes = (ttl_value % (60 * 60)) // 60  # 59分钟
    seconds = ttl_value % 60  # 14秒
    return f"{days}天 {hours}小时 {minutes}分钟 {seconds}秒"


def convert_model_to_dict(obj: Any, *args, **kwargs):
    """辅助函数，将Pydantic V1版本中的UUID/Enum等数据转换成可序列化存储的数据。"""
    # 1.如果是Pydantic的BaseModel类型，递归处理其字段
    if isinstance(obj, BaseModel):
        print("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk")
        obj_dict = obj.dict(*args, **kwargs)
        # 2.递归处理嵌套字段
        for key, value in obj_dict.items():
            obj_dict[key] = convert_model_to_dict(value, *args, **kwargs)
        return obj_dict

    # 3.如果是 UUID 类型，转换为字符串
    elif isinstance(obj, UUID):
        return str(obj)

    # 4.如果是 Enum 类型，转换为其值
    elif isinstance(obj, Enum):
        return obj.value

    # 5.如果是列表类型，递归处理列表中的每个元素
    elif isinstance(obj, list):
        return [convert_model_to_dict(item, *args, **kwargs) for item in obj]

    # 6.如果是字典类型，递归处理字典中的每个字段
    elif isinstance(obj, dict):
        return {key: convert_model_to_dict(value, *args, **kwargs) for key, value in obj.items()}

    # 7.对其他类型的字段，保持原样
    return obj


def format_datetime(value):
    """格式化为中文习惯的日期时间"""
    if hasattr(value, 'strftime'):
        return value.strftime('%Y-%m-%d %H:%M:%S')  # 2025-10-13 15:47:31
    elif isinstance(value, str):
        # 尝试解析并重新格式化
        try:
            from datetime import datetime
            for fmt in ['%a, %d %b %Y %H:%M:%S GMT', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d']:
                try:
                    dt = datetime.strptime(value, fmt)
                    return dt.strftime('%Y-%m-%d %H:%M:%S')
                except ValueError:
                    continue
            return value
        except:
            return value
    else:
        return value


def serialize_model(obj, fields_to_include):
    """安全序列化模型对象，使用中文习惯的日期格式"""
    if not obj:
        return {}

    result = {}
    for field in fields_to_include:
        if hasattr(obj, field):
            value = getattr(obj, field)

            # 对日期时间字段统一格式化
            if field in ['created_at', 'updated_at']:
                result[field] = format_datetime(value)
            else:
                result[field] = value

    return result